package it.enricod.jcontextfree.engine;

import it.enricod.jcontextfree.engine.model.IProgram;
import it.enricod.jcontextfree.engine.sablecc.lexer.Lexer;
import it.enricod.jcontextfree.engine.sablecc.lexer.LexerException;
import it.enricod.jcontextfree.engine.sablecc.node.Start;
import it.enricod.jcontextfree.engine.sablecc.parser.Parser;
import it.enricod.jcontextfree.engine.sablecc.parser.ParserException;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PushbackReader;
import java.io.StringReader;

public class ProgramLoader implements IProgramLoader {

    public ProgramLoader() {

    }
    
	public IProgram load(File program) throws FileNotFoundException {
		String programAsText = TextFileReader.getContents(new File(program.getAbsolutePath()));
		return load(programAsText);
	}

	public IProgram load(String programAsText) {
		Lexer lexer = new Lexer(new PushbackReader(new StringReader(programAsText)));
		Parser parser = new Parser(lexer);
		Start ast;
		try {
			ast = parser.parse();
			/* Get our Interpreter going. */
			JCFProgramInterpreter interp = new JCFProgramInterpreter();
			ast.apply(interp);

			IProgram result = interp.getProgram();
			result.setText(programAsText);
			return result;
		} catch (ParserException e) {
			e.printStackTrace();
		} catch (LexerException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}
}
